package com.gadgets.busi.bm05.controller;

import com.alibaba.fastjson.JSON;
import com.gadgets.busi.bm05.common.SVNRepositoryUtil;
import com.gadgets.busi.bm05.common.SVNTagsCommitDTO;
import com.gadgets.busi.bm05.common.SvnKetTagsRequestDTO;
import com.gadgets.framework.common.dto.HttpBaseResp;
import com.gadgets.framework.common.exception.GadgetsServiceException;
import com.gadgets.framework.common.util.FileOperUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tmatesoft.svn.core.ISVNLogEntryHandler;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.io.SVNRepository;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @author UncleXiu
 * @version V1.0.0
 * @data 2022-03-02
 */
@RestController
@RequestMapping(value = "/svnkit")
public class SvnKitController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${spring.downloadPath}")
    private String downloadPath;

    @RequestMapping(value = "/tagScan.do")
    public HttpBaseResp<String> scanTagsFile(HttpServletRequest request, HttpServletResponse response,final SvnKetTagsRequestDTO tagsRequestDTO) throws GadgetsServiceException, SVNException {
        SVNRepository repository = SVNRepositoryUtil.getBBSPRepository(tagsRequestDTO.getBankName());
        HashMap<String, List<SVNTagsCommitDTO>> commitHashMap = new HashMap<>();
        try {
            repository.log(
                new String[0],
                0,
                -1,
                true,
                true,
                new ISVNLogEntryHandler() {
                    @Override
                    public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {
                        // 如果是目标人提交的记录，则记录为tags文件
                        logger.debug("发现日志：{}", JSON.toJSONString(logEntry));
                        if(tagsRequestDTO.getCommitAuthor().contains(logEntry.getAuthor())){
                            logger.info("发现{}的提交日志，版本:{}", logEntry.getAuthor(), logEntry.getRevision());
                            for (Object commitFileNameInfo : logEntry.getChangedPaths().keySet()) {
                                String fileName = (String) commitFileNameInfo;
                                if(fileName.contains("/src/")) {
                                    fileName = fileName.substring(fileName.indexOf("/src/"));
                                    if (!commitHashMap.containsKey(fileName)) {
                                        commitHashMap.put(fileName, new ArrayList<>());
                                    }
                                    SVNTagsCommitDTO commitDTO = new SVNTagsCommitDTO();
                                    commitDTO.setVersion(logEntry.getRevision());
                                    commitDTO.setAuthor(logEntry.getAuthor());
                                    commitDTO.setComomitComment(logEntry.getMessage());
                                    commitDTO.setCommitDate(logEntry.getDate());
                                    commitDTO.setFileName(fileName);
                                    commitHashMap.get(fileName).add(commitDTO);
                                }
                            }
                        }
                    }
                }
            );
        } catch (SVNException e) {
            throw new GadgetsServiceException(e);
        }
        HashMap<String, List<SVNTagsCommitDTO>> retMap = new HashMap<>();
        for (String fileName : commitHashMap.keySet()) {
            if(SVNRepositoryUtil.fileName.contains(fileName)){
                retMap.put(fileName, commitHashMap.get(fileName));
                retMap.get(fileName).sort(null);
            }
        }
        String jsonString = JSON.toJSONString(retMap, true);
        logger.info("扫描结果：{}",jsonString);
        String fileUUID = UUID.randomUUID().toString();
        FileOperUtil.writeTxtTotFile(downloadPath+"/tags扫描-"+fileUUID+".txt",jsonString);
        // 告知前端文件名
        HttpBaseResp<String> resp = new HttpBaseResp<>();
        resp.setErrorMsg(fileUUID);
        return resp;
    }

}
